#include <string.h>
#include "ftpputfile.h"

FtpGet::FtpGet(QObject *parent)
        : QObject(parent)
{
    dirIsExist = 1;
    connect(&ftp, SIGNAL(done(bool)), this, SLOT(ftpDone(bool)));
    connect(&ftp, SIGNAL(listInfo(QUrlInfo)), this, SLOT(ftpListInfo(QUrlInfo)));
    connect(&ftp, SIGNAL(commandFinished(int,bool)), this, SLOT(ftpCommandFinished(int,bool)));
}

bool FtpGet::putFile(const QString &filename)
{
    file.setFileName(filename);
    if(file.isOpen())
    {
        file.close();
    }

    file.setFileName(filename);
    file.open(QIODevice::ReadOnly);

    ftp.connectToHost("192.168.131.126", 21);
    printf("start connect to host\n");

    ftp.login("lvyongbo", "123456");
    printf("start login\n");

    //ftp.list();

    if(dirIsExist){
        mkdirId = ftp.mkdir("lvyongbo1");
    }

    ftp.cd("lvyongbo1");

    filebuffer = file.readAll();
    file.close();

    ftp.put(filebuffer, "test2");
    printf("start put\n");
    ftp.close();

    return true;
}


bool FtpGet::justputFile(void)
{

    ftp.cd("lvyongbo1");

    printf("file size is %lld\n", file.size());
    printf("filebuffer is %d\n", filebuffer.size());
    ftp.put(filebuffer, "test3");
    ftp.close();

    return true;
}


void FtpGet::ftpDone(bool error){

    if(error){
        printf("ftpDone error\n");
    }
    else{
        printf("ftpDone success\n");
    }

    if(file.isOpen()){
        file.close();
    }

}

void FtpGet::ftpListInfo(const QUrlInfo &url){

    printf("ftpListInfo is %s\n", url.name().toLocal8Bit().data());

    if(url.isDir() && !url.isSymLink())
    {
        if(strstr(url.name().toLocal8Bit().data(), "lvyongbo2")){
            printf("The dir is exist\n");
            dirIsExist = 1;
        }
        else{
            printf("The dir is not exist\n");
            dirIsExist = 0;
        }
    }

    return;
}

void FtpGet::ftpCommandFinished(int id, bool error){
    if(mkdirId == id){
        if(error){
            printf("dirIsExist = 0\n");
            dirIsExist = 0;
            emit justputFile();
        }
        else{
            dirIsExist = 1;
        }
    }


}

